<template>
	<view class="home">
		<view class="home__head" :style="{'padding-top': barHeight + 'rpx'}">
			<view class="home__head-mask"></view>
			<view class="home__head-weather" @click="goWeather">
				<view class="home__head--top">
					<view class="home__head-weather-icon" v-if="iconId">
						<image :src="iconId" mode=""></image>
					</view>
					<view class="home__head-weather-temp" v-if="temperature">{{temperature}}℃</view>
				</view>
				<view class="home__head--bottom">
					<view class="home__head--bottom-icon"></view>
					<view class="home__head--bottom--content">{{city}}</view>
				</view>
			</view>
			<view class="home__head-notice" @click="clickNotice">
				<u-badge type="warning" max="99" :offset="[-7,-6]" style="z-index: 9;" bgColor="#f5222d" absolute :value="unReadCount"></u-badge>
				<image src="@/static/theme/default/home/dongtai.png" mode=""></image>
			</view>
			<view class="home__head-change-factory" @click="clickFactoryIcon" v-if="factorys.length > 1">
				<image src="@/static/theme/default/home/change.png" mode=""></image>
			</view>
		</view>
		<view class="home__body">
			<view class="home__body-bg"></view>
			<view class="home__body--box">
				<view class="home__body--box-item" v-for="item in list" :key="item.Id" @click="throttle(item)">
					<view class="home__body--box-item-icon" :style="{'background-color': item.ModuleTheme}" hover-class="clickable">
						<image :src="item.icon" mode=""></image>
					</view>
					<view class="home__body--box-item-text">{{item.ModuleName}}</view>
				</view>
				<view class="home__body--box-item" @click="goModuleSetting">
					<view class="home__body--box-item-icon">
						<image src="../../static/theme/default//home/more.png" mode=""></image>
					</view>
					<view class="home__body--box-item-text">更多</view>
				</view>
				<view class="home__body--box-item" v-if="((list.length + 1) %4) !== 0" v-for="n in (4-(list.length + 1) %4)"></view>
			</view>
		</view>
		<view class="home__bottom">
			<view class="card">
				<view class="card__head">
					<view class="card__head--left">
						<view class="card__head--left-icon">
							<image src="../../static/theme/default//home/shu2.png" mode=""></image>
						</view>
						<view class="card__head--left-text">实时数据</view>
					</view>
					<view class="card__head--right" style="margin-right: 20rpx;">
						<view class="card__head--right-item" style="margin-right: 30rpx;" @click="goChart">
							<image src="../../static/theme/default//home/zhexian.png" mode=""></image>
							<view style="z-index: 9;">指标</view>
						</view>
						<view class="card__head--right-item" @click="goKwh">
							<image src="../../static/theme/default//home/shuizhi.png" mode=""></image>
							<view style="z-index: 9;">电耗</view>
						</view>
					</view>
				</view>
				<view class="card-body">
					<view class="card-item" v-for="item in data" @click="goCurrentChart(item)"  hover-class="clickable">
						<view class="card-item__bg1"></view>
						<view class="card-item__bg2"></view>
						<view class="card-item-yujing" v-show="item.stat != '13' && item.stat != ''">
							<image src="../../static/theme/default/home/yujing.png" mode=""></image>
						</view>
						<view class="card-item__value">{{item.value}}<text>{{item.unit}}</text></view>
						<view class="card-item__text">{{item.text}}</view>
						<view class="card-item__place">
							<image class="card-item__place--icon" src="../../static/theme/default/home/place.png"></image>
							<view class="card-item__place--text">{{place}}</view>
						</view>
					</view>
				</view>
			</view>
			<view class="card">
				<view class="card__head">
					<view class="card__head--left">
						<view class="card__head--left-icon">
							<image src="../../static/theme/default//home/shu2.png" mode=""></image>
						</view>
						<view class="card__head--left-text">我的关注</view>
					</view>
					<view class="card__head--right" @click="goCnl">更多</view>
				</view>
				<u-skeleton rows="6" :title="false" :loading="true" :animate="true" rowsHeight="60" v-if="!cnlVisible"></u-skeleton>
				<view class="cnl-list" v-else-if="focusCnls.length">
					<view class="list-item" v-for="item in focusCnls"  hover-class="clickable" @click="goDeviceCnl(item)">
						<view class="list-item-hover" hover-class="clickable">
							<view class="list-item-left">
								<view class="cnl-title">{{item.DeviceName}}</view>
								<view class="cnl-code">{{item.buwei}}<text style="margin: 0 10rpx;">{{item.DeviceCode}}</text><text style="font-size: 20rpx;color: #aaa;"> {{item.des}}</text></view>
							</view>
							<view class="list-item-right">
								<view class="list-item-right-top">
									<view class="cnl-val" v-if="item.Type != 1">{{item.Val}} {{item.Unit}}</view>
									<view class="cnl-val" v-else>
										<image src="../../static/theme/default/home/jihuo.png" mode="" v-if="item.Val == 1"></image>
										<image src="../../static/theme/default/home/weijihuo.png" mode="" v-if="item.Val == 0"></image>
									</view>
									<view class="list-item-icon">
										<image src="../../static/theme/default/home/yujing.png" mode="" v-if="item.Stat != '13' && item.Stat != ''"></image>
									</view>
									<view class="" style="clear: both;"></view>
								</view>
								<view class="cnl-datetime">{{item.DateTime}}</view>
							</view>
						</view>
					</view>
				</view>
				<u-button :customStyle="{backgroundColor: 'rgba(0,153,229,.3)',color: '#fff',fontSize: '50rpx'}" @click="goEquipment" v-else>+</u-button>
			</view>
		</view>
		
		<!-- 解决滚动穿透问题 -->
		<view class="" @touchmove.stop.prevent="preventHandler">
			<u-popup :show="showFactoryPop" mode="center" @close="showFactoryPop = false" @open="showFactoryPop = true">
				<view class="popup-box">
					<view class="popup-box-item" v-for="item in factorys" @click="changePlace(item)">
						<view>{{item.aname}}</view>
						<uni-icons type="checkmarkempty" size="20" v-if="item.aname == place"></uni-icons>
					</view>
				</view>
			</u-popup>
		</view>
		
		<Update></Update>
	</view>
</template>

<script>
	import _data from '@/common/_data.js';
	import _custom from '@/common/_custom.js';
	import _get from '@/common/_get.js';
	import _hook from '@/common/_hook.js'
	import moment from 'moment'
	import {formatImg,getTableSuffix,throttle,goScanCode,setDotNumber} from '@/common/custom_util.js'
	import weatherIcon from '@/pages/home/child/weather/weather.js';
	import Update from '@/components/update/update.vue';
	import IconFont from '../../components/custom/icon-font/index.vue' 
	
	export default {
		components: {
			Update,IconFont
		}, 
		data() {
			return {
				pxid: _data.localData('userid'),
				list: [],
				data: [
					{
						value: '',
						text: '出水瞬时流量',
						unit: 'm³',
						stat: '',
						option: {
							name: '水量',
							lineColor: '#3CA272'
						},
						params: {
							in: 'Y2G2M03LL',
							out: 'P1E1M06SSL',
						}
					},
					{
						value: '',
						text: '出水COD',
						unit: 'mg/L',
						stat: '',
						option: {
							name: 'COD',
							lineColor: '#7B2CFF'
						},
						params: {
							in: 'Y1J1M01JKCOD',
							out: 'P1E1M01CKCOD'
						}
					},
					{
						value: '',
						text: '出水TN',
						unit: 'mg/L',
						stat: '',
						option: {
							name: 'TN',
							lineColor: '#FF81C0'
						},
						params: {
							in: 'Y1J1M03JKZD',
							out: 'P1E1M03CKZD'
						}
					},
					{
						value: '',
						text: '出水TP',
						unit: 'mg/L',
						stat: '',
						option: {
							name: 'TP',
							lineColor: '#03FAFB'
						},
						params: {
							in: 'Y1J1M04JKZL',
							out: 'P1E1M04CKZL'
						}
					},
					{
						value: '',
						text: '出水NH3·N',
						unit: 'mg/L',
						stat: '',
						option: {
							name: 'NH3',
							lineColor: '#FA9F10'
						},
						params: {
							in: 'Y1J1M02JKAD',
							out: 'P1E1M02CKAD'
						}
					},
					{
						value: '',
						text: '出水PH',
						unit: '',
						stat: '',
						option: {
							name: 'pH',
						},
						params: {
							in: '',
							out: 'P1E1M05CKPH'
						}
					},
					
				],
				barHeight: 0,
				city: '',
				temperature: '',
				place: '',
				focusCnls: [],
				obsusername: '',
				cnlVisible: false,
				appModuleIds: '',
				weather: '',
				weatherIcon: weatherIcon,
				iconId: '',
				weatherTime: '',
				showFactoryPop: false,
				factorys: [],
				obscode: '',
				throttle: null,
				unReadCount: 0,//未读数
			} 
		},
		onLoad() {
			let that = this;
			try {
				this.obscode = _data.localData('obscode');
				this.temperature = _data.localData('temperature') ? _data.localData('temperature') : '';
				this.weatherTime = _data.localData('weather-time') ? _data.localData('weather-time') : '1970-01-01';
				this.throttle = throttle(this.goPath,100);
			} catch(e) {
				console.log(e)
			}
		},
		onShow() {
			let that = this;
			this.init();
			uni.$on('follow-cnl-code-data',(res) => {
				try {
					let temp = []
					if(res.length && Object.keys(res[0]).length) {
						for (let index in res) {
							if(res[index].Type == '0') {
								res[index].Val = res[index].Val ? setDotNumber(res[index].Val) : ''
							}
							if(res[index].Unit == '无') {
								res[index].Unit = ''
							}
							if(index < 6) {
								temp.push(res[index])
							}
							res[index].des = res[index].Name
						}
					}
					this.focusCnls = temp;
					this.cnlVisible = true;
				} catch(e) {
					console.log(e)
				}
			})
			uni.$on('default-cnl',(data) => {
				try {
					data.forEach((item,index) => {
						this.data.forEach(v => {
							if(v.params.out == item.CnlCode && item.CnlCode != 'P1E1M06SSL') {
								let val = item.Val*1
	
								// var p = item.Val.indexOf('.'); 
								var p = item.Val;
								//小数点的位置
								if(p > 0) {
									v.value = val ? val.toFixed(2) : ''
								} else {
									v.value = val
								}
								v.stat = item.Stat
							}
						})
					})
				} catch(e) {
					console.log(e)
				}
			})
			uni.$on('weather',(res) => {
				if(!res.length) {
					that.iconId = ''
					that.city = ''
					return
				}
				try {
					let data = res[0];
					if(data['FutureInfo1'] && that.weatherIcon != null) {
						let temp = JSON.parse(unescape(data['FutureInfo1']))
						for (let i = 0; i < that.weatherIcon.length; i++) {
							if(temp.wid.day == that.weatherIcon[i].wid) {
								let index = that.weatherIcon[i].icon.indexOf('-')
								let icon = that.weatherIcon[i].icon.substring(index+1)
								that.iconId = require('@/static/theme/default/weather/' + icon + '.png')
							}
						}
						that.city = data.City
						that.weather = data.FutureInfo1.weather
					}
				} catch(e) {
					console.log(e)
				}
			})
		},
		onReady() {
			_hook.routeTabBarHook();
			let that = this;
			// #ifdef APP-PLUS  
			uni.getSystemInfo({ 
				success: function(e) {
					let barHeight = 0;
					if (e.platform == 'android') {
						that.barHeight = e.statusBarHeight + 50
					} else {
						barHeight = e.statusBarHeight + 45
					}
				}
			})
			// #endif
		},
		onHide() {
			uni.$off('weather')
			uni.$off('follow-cnl-code-data')
			uni.$off('default-cnl')
		},
		onPullDownRefresh() {
			this.init()
			setTimeout(() => {
				uni.stopPullDownRefresh()
			},1000)
		},
		methods: {
			/**
			 * 页面初始化
			 */
			init() {
				this.obsusername = _data.localData('name');
				try {
					this.place = _data.localData('obsname');
				} catch(e) {
					console.log(e)
				}
				this.getAppModuleUserPower();
				this.getFocusCnls()
				this.getDefaultCnlCodeData()
				this.getDefaultFollowCnlCodeMergeData()
				this.getCompanyInfo()
				this.getFactorys()
				this.getTopicUnReadCount();
				this.getWeather();
				this.getUserInfo();
			},
			/**
			 * 获取模块数据
			 */
			getAppModuleUserPower() {
				let that = this;
				_custom.getDataJava({
					apiname: 'getAppModuleUserPower',
					apiparam: {
						obsusername: that.obsusername
					},
					success(response) {
						try {
							let temp = [];
							let list = [];
							response.forEach(item => {
								item.icon = formatImg(item.ModuleImage)
								if(item.Sorting != '99') temp.push(item)
							})
							if(temp.length) {
								temp.forEach((v,i) => {
									temp.forEach((item,index) => {
										if(item.Sorting == (i+1)) list.push(item)
									})
								})
								that.list = list;
								return
							}
							if(response.length < 11) {
								that.list = response;
							} else {
								that.list = response.splice(0,11);
							}
						} catch (e) {
							console.log(e)
						}
					}
				})
			},
			/**
			 * 获取水厂数据
			 */
			getFactorys() {
				let that = this;
				_custom.getDataJava({
					apiname: 'getUserObsList',
					apiparam: {
						username: _data.localData('phone'),
					},
					success(res) {
						that.factorys = res
					}
				})
			},
			/**
			 * 获取默认实时数据
			 */
			getDefaultCnlCodeData() {
				let that = this
				_custom.getDataJava({
					name: 'default-cnl',
					apiname: 'getDefaultFollowCnlCodeData',
					apiparam: {
						obscode: this.obscode,
						tablesuffix: getTableSuffix()
					},
					fail(res) {
						that.data.forEach(v => {
							v.value = ''
							v.stat = ''
						})
					}
				})
			},
			/**
			 * 获取实时数据中的出水瞬时流量（由于是多个进水口，需要单独调）
			 */
			getDefaultFollowCnlCodeMergeData () {
				let that = this;
				_custom.getDataJava({
					apiname: 'getDefaultFollowCnlCodeMergeData',
					apiparam: {
						obscode: this.obscode,
						mergetag: 2,
						tablesuffix: getTableSuffix()
					},
					success(res) {
						try {
							if(res.length && Object.keys(res[0]).length) {
								let val = res[0].Val*1
								var p = res[0].Val.toString().indexOf('.');   //小数点的位置
								if(p > 0) {
									
									that.data[0].value = val.toFixed(2)
								} else {
									that.data[0].value = val
								}
								that.data[0].unit = res[0].Unit;
								that.data[0].stat = res[0].Stat;
							}
						} catch(e) {
							console.log(e)
						}
					},
					fail() {
						that.data.forEach(v => {
							v.value = ''
							v.stat = ''
						})
					}
				})
			},
			/**
			 * 缓存管理员判断字段
			 */
			getUserInfo() {
				_custom.getDataJava({
					apiname: 'getUserInfo',
					apiparam: {
						obsusername: this.obsusername
					},
					success(res) {
						console.log("用户数据",res);
						if(res.length) {
							_data.localData('isMaster',res[0].IsMaster)
							_data.localData('ctrlScada',res[0].CtrlScada)
						}
					},
					fail() {
						_data.localData('isMaster','0')
					}
				})
			},
			/**
			 * 跳转实时数据图表界面
			 */
			goChart( ){
				uni.navigateTo({
					url: './child/chart/index'
				})
			},
			/**
			 * 跳转到电耗界面
			 */
			goKwh() {
				uni.navigateTo({
					url: './child/kwh'
				})
			},
			/**
			 * 跳转当前点击的实时数据图表界面
			 */
			goCurrentChart(v) {
				uni.navigateTo({
					url: './child/chart/current?data='+JSON.stringify(v)
				})
			},
			/**
			 * 跳转模块对应的页面
			 * @param {Object} v 模块列表中的单个对象
			 */
			goPath(v) {
				let ModuleRouter = v.ModuleRouter;
				let path = ModuleRouter.split('?')[0];
				let param = ModuleRouter.split('?')[1];
				param = 'name=' + v.ModuleName + '&' + param;
				if(path == 'scancode') {
					// #ifdef APP-PLUS
						goScanCode()
					// #endif
				}else if(path){
					let url = './child/' + path + '/index?' + param
					uni.navigateTo({
						url: url,
						fail(err) {
							uni.showToast({
								title: '功能开发中...',
								icon: 'none'
							})
						}
					});
				} else {
					uni.showToast({
						title: '功能开发中...',
						icon: 'none'
					})
				}
			},
			/**
			 * 获取天气（EOD接口）
			 */
			getWeather() {
				let that = this;
				_custom.getDataJava({
					name: 'weather',
					apiname: 'getWeather',
					apiparam: {
						obsdate: moment().format('YYYY-MM-DD'),
					},
					fail(res) {
						that.iconId = ''
						that.city = ''
					}
				})
			},
			/**
			 * 获取单位数据（第三方接口，包含天气数据）
			 */
			getCompanyInfo() {
				let that = this;
				_custom.getDataJava({
					apiname: 'getCompanyInfo',
					success(res) {
						try {
							let company = res.length ? res[0] : {};
							if(that.weatherTime) {
								let time = new Date(that.weatherTime)
								let diff = moment().diff(time,'hours')
								if(diff > 2) {
									uni.request({
										url: 'https://restapi.amap.com/v3/weather/weatherInfo?key=42f1ef980a0b3f10e555dab937b4f906&city=' + company.CityName,
										success(res) {
											that.temperature = res.data.lives[0].temperature;
											_data.localData('temperature',that.temperature)
											let t = moment().format('x')
											_data.localData('weather-time',t)
										},
										fail(e) {
											uni.showToast({
												title: '获取天气失败',
												icon: 'none'
											})
										}
									})
								}
							}
						} catch(e) {
							console.log(e)
						}
					}
				})
			},
			/**
			 * 获取点位关注列表
			 */
			getFocusCnls() {
				let that = this;
				_custom.getDataJava({
					name: 'follow-cnl-code-data',
					apiname: 'getFollowCnlCodeData',
					apiparam: {
						obsusername: this.obsusername,
						tablesuffix: getTableSuffix()
					},
					fail(res) {
						that.focusCnls = []
					}
				})
			},
			/**
			 * 获取主题回复相关未读数量
			 */
			getTopicUnReadCount() {
				let that = this;
				_custom.getDataJava({
					apiname: 'getTopicUnReadCount',
					apiparam: {
						obsusername: this.obsusername,
						obspxid: this.pxid
					},
					success(res) {
						let sum = 0;
						if(res.length) {
							sum += res[0].LikesUnReadCount ? (res[0].LikesUnReadCount*1) : 0
							sum += res[0].ReplyUnReadCount ? (res[0].ReplyUnReadCount*1) : 0
							sum += res[0].AtUnReadCount ? (res[0].AtUnReadCount*1) : 0
						}
						that.unReadCount = sum;
					}
				})
			},
			/**
			 * 跳转关注页
			 */
			goCnl() {
				uni.navigateTo({
					url: './child/focus',
				});
			},
			/**
			 * 跳转设备台账页
			 */
			goEquipment() {
				uni.navigateTo({
					url: './child/equipment/index',
				});
			},
			/**
			 * 跳转模块编辑页
			 */
			goModuleSetting() {
				uni.navigateTo({
					url: './child/module/index',
				});
			},
			/**
			 * 跳转点位页
			 */
			goDeviceCnl(v) {
				uni.navigateTo({
					url: '/pages/home/child/equipment/cnl?data=' + JSON.stringify(v)
				})
			},
			/**
			 * 跳转天气页
			 */
			goWeather() {
				uni.navigateTo({
					url: './child/weather/index',
				});
			},
			/**
			 * 切换水厂
			 * @param {Object} v 水厂列表中的对象
			 */
			changePlace(v) {
				this.obscode = v.OBSCODE;
				_data.localData('obscode',v.OBSCODE);
				_data.localData('obsname',v.aname);
				_data.localData('weather-time','1970-01-01');
				this.weatherTime = '1970-01-01';
				this.place = v.aname;
				this.showFactoryPop = false;
				this.init();
			},
			/**
			 * 点击水厂图标
			 */
			clickFactoryIcon() {
				this.showFactoryPop = true;
			},
			/**
			 * 跳转动态页
			 */
			clickNotice() {
				uni.navigateTo({
					url: './child/notice/index',
					animationType: 'none',
				})
			},
			/**
			 * 阻止滑动默认事件
			 */
			preventHandler() {
				return
			}
		}
	}
</script>

<style>
	@import url(./index.css);
</style>